﻿using ApiLib.AppStart;
using ApiLib.Helpers;
using ApiLib.Utils;
using Furion.Schedule;

namespace ApiLib.Common.MyJobs;

/// <summary>
/// 我的定时任务，用于刷新程序执行时间，同步数据库系统配置
/// </summary>
[PeriodMinutes(3, RunOnStart = true)]
public class DefaultJob : IJob
{
    /// <summary>
    /// 系统启动时间
    /// </summary>
    private static readonly DateTime StartTime = DateTime.Now;

    private static int _day;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    public Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        var now = DateTime.Now;
        if (now.Day != _day)
        {
            if (_day != 0)
            {
                var ts = now - StartTime;
                WebUtil.LogSys($"启动时间：{StartTime}");
                WebUtil.LogSys($"当前时间：{now}");
                WebUtil.LogSys($"系统已持续运行：{ts.Days}天{ts.Hours}小时{ts.Minutes}分钟{ts.Seconds}秒");
            }

            _day = now.Day;
        }

        if (GlobalConfig.UseDb)
        {
            try
            {
                var configs = DbHelper.GetAllSystemConfig();
                foreach (var sysConfig in configs)
                {
                    GlobalConfig.SystemConfigs[sysConfig.Key] = sysConfig.Value;
                }
            }
            catch (Exception)
            {
                WebUtil.LogExp("读取数据库配置文件异常！");
            }
        }

        RunOnStart();

        return Task.CompletedTask;
    }


    /// <summary>
    /// 是否第一次
    /// </summary>
    private static bool _first = true;

    /// <summary>
    /// 开始时执行
    /// </summary>
    private void RunOnStart()
    {
        if (!_first)
        {
            return;
        }

        _first = false;
        
        WebUtil.LoadSchedule(); //加载定时任务
    }
}